const fs = require('fs')
const chalk = require('chalk')
var sqlite3 = require('sqlite3').verbose();

const db_file = 'sqlite.db'
if (!fs.existsSync(db_file)) {
    console.log("creating db file");
    fs.openSync(db_file, 'w', function () { });
}
function get_meta(tablename) {
    var db = new sqlite3.Database(db_file);
    const sql= `SELECT * FROM \`sqlite_master\` where \`type\`='table' and name='${tablename}'`;
    const sql_cols = 'pragma table_info('+tablename+')'
    // console.log(chalk.green(sql))
    return new Promise((resolve,reject) => {
        db.all(sql_cols, function (err, res) {
            // console.log('!!!!!!!!',err, row);
            if(err) reject(err)
            else resolve(res)
        });
        db.close();
    })
}
function db_init(db_file) {
    var db = new sqlite3.Database(db_file);

    db.serialize(function () {
        // 创建表 people 并注入10行演示数据
        db.run("CREATE TABLE people (name text,info TEXT)", function (err) {
            console.error('建表结果', !err)
            if (!err) {
                var stmt = db.prepare("INSERT INTO people VALUES (?,?)");
                for (var i = 0; i < 10; i++) {
                    stmt.run('man@' + i, i % 2 === 0 ? 'man' : 'woman');
                }
                stmt.finalize();
            }
        });
        // 创建性别表
        db.run("CREATE TABLE sex (v TEXT,name TEXT)",function(err){
            console.error('建表结果',!err)
            var stmt = db.prepare("INSERT INTO `sex` VALUES (?,?)");
            stmt.run('1','male');
            stmt.run('0','female');
            stmt.finalize();
        });
        // 演示,非必须
        db.each("SELECT name,info FROM people", function (err, row) {
            console.log(row.name + ": " + row.info);
        });
        // 演示,非必须
        console.log('-----')
        db.each("SELECT * FROM `sqlite_master`", function (err, row) {
            console.log(err, row);
        });
    });
    db.close()
}
// db_init(db_file)
module.exports = function (plop) {
    plop.setGenerator('test2', {
        description: 'this is a skeleton plopfile',
        prompts: [
            {
                type: 'input',
                name: 'name',
                message: 'input your name'
            },
            {
                type: 'input',
                name: 'tablename',
                message: 'input your tablename'
            },
            {
                when: function (a) { //决定这个问题问不问
                    console.log('when get,', a)
                    return a.tablename == 'table'
                },
                type: 'confirm',
                name: 'tablename_confirm',
                message: '确认使用保留字命名的表吗'
            },
            {
                when: function (answers) {
                    if (answers.tablename_confirm === false) {
                        throw 'aborting';
                    }
                    return true
                },
                name: 'cols',
                message: 'select 列',
                type: 'checkbox',
                choices: async function (here) {
                    console.log('choice here', here)
                    console.log('table name your select is',here.tablename)
                    var meta = await get_meta(here.tablename);
                    console.log('meta get:::::',meta)
                    if(meta.length===0){
                        console.error('表不存在')
                        process.exit(0)
                    }
                    return meta.map(s=>({
                        name: s.name.toUpperCase(),
                        value: s.name,
                        checked: true
                    }))
                },
                validate: function (value) {
                    if (value.length>0)
                        return true;
                    return '表不存在';
                }
            },
            {
                when(anwsers) {
                    return anwsers.cols.length === 0
                },
                name: 'columns',
                description: '固定选择',
                message: 'select your cols',
                type: 'checkbox',
                choices: [
                    { name: 'Cheese', value: 'cheese', checked: true },
                    { name: 'Pepperoni', value: 'pepperoni' },
                    { name: 'Pineapple', value: 'pineapple' },
                    { name: 'Mushroom', value: 'mushroom' },
                    { name: 'Bacon', value: 'bacon', checked: true }
                ]
            }
        ], // array of inquirer prompts
        actions: [
            function (answers) {
                console.log(chalk.blue('hello'), chalk.red(`${answers.name}`));
                console.log(`from table:${answers.tablename} ,you seelected:`, answers.cols);
            }
        ]  // array of actions
    });
};